package leetcode;

import java.util.Arrays;

/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q2570.java
 * @Author : WangRuoyu
 * @Date 2023/2/23 10:10
 */

public class Q2570 {
    public int[][] mergeArrays(int[][] nums1, int[][] nums2) {
        int[][] tmp = new int[nums1.length + nums2.length][2];

        int p = 0;
        int q = 0;
        int index = 0;

        while ((p < nums1.length) && (q < nums2.length)) {
            if (nums1[p][0] < nums2[q][0]) {
                tmp[index][0] = nums1[p][0];
                tmp[index][1] = nums1[p][1];
                index++;
                p++;
            } else if (nums1[p][0] > nums2[q][0]) {
                tmp[index][0] = nums2[q][0];
                tmp[index][1] = nums2[q][1];
                index++;
                q++;
            } else {
                tmp[index][0] = nums2[q][0];
                tmp[index][1] = nums1[p][1] + nums2[q][1];
                index++;
                p++;
                q++;
            }
        }

        if (nums1.length == p) {
            while (q < nums2.length) {
                tmp[index][0] = nums2[q][0];
                tmp[index][1] = nums2[q][1];
                index++;
                q++;
            }
        } else {
            while (p < nums1.length) {
                tmp[index][0] = nums1[p][0];
                tmp[index][1] = nums1[p][1];
                index++;
                p++;
            }
        }

        int[][] res = new int[index][2];

        for (int i = 0; i < index; ++i) {
            res[i] = tmp[i];
        }

        return res;
    }

    public static void main(String[] args) {
        Q2570 sl = new Q2570();
        int[][] nums1 = {{1, 2}, {2, 3}, {4, 5}};
        int[][] nums2 = {{1, 4}, {3, 2}, {8, 1}};
        for (int[] a : sl.mergeArrays(nums1, nums2)) {
            System.out.println(Arrays.toString(a));
        }
    }
}